#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Lee
# @File    : dhy_linear_accuracy_main_view.py
# @Time    : 2024/2/1 10:56
import os
import json
from util.global_config import *
from PyQt5 import QtCore, QtWidgets
from views.resource_view.linear_accuracy_main_view import Ui_DHYLocalizationTestView
from views.matplotlib_view import MplWidget
from util.get_localization_points import *
from views.alert_messagebox_view import *
from util.analysis_record_bag import *
# from views.dhy_ab_dialog import DHYABDialog
# from views.dhy_a_plus_dialog import DHYAPlusDialog
from views.dhy_online_dis_view import DHYOnlineDisView
from views.dhy_connect_row_view import DHYConnectRowView
from views.dhy_threshold_dialog import DHYThresholdDialog
from views.dhy_cut_trajectory_view import DHYCutTrajectoryView
from views.dhy_resource_collection_view import show_dhy_resource_collection_view
from views.dhy_anti_interference_endurance_view import DHYAntiInterferenceEnduranceView


class DHYMainWindow(QtWidgets.QMainWindow, Ui_DHYLocalizationTestView):
    def __init__(self, parent=None):
        super(DHYMainWindow, self).__init__(parent)
        self.setupUi(self)

        self.csv_file_path = None
        self.global_config = global_config
        self.localization_points_from_csv = None

        # 添加matplotlib视图
        matplotlib_widget = MplWidget(self)
        self.matplotlib_layout.addWidget(matplotlib_widget)
        self.matplotlib_view = matplotlib_widget.qCanvas

        self.ABLine.setChecked(True)
        # 监听测试类别
        self.ABLine.clicked.connect(lambda: self.test_type_changed("ab_line"))
        self.APlusLine.clicked.connect(lambda: self.test_type_changed("a_plus_line"))

        # 点击菜单栏中“文件” -> “打开csv”
        self.action_open_csv.triggered.connect(self.select_csv_file)
        # 点击菜单栏中“文件” -> “重载数据”
        self.action_reload_csv.triggered.connect(self.load_csv_data)
        self.action_set_threshold.triggered.connect(self.set_threshold)
        self.action_connect_row_points.triggered.connect(self.connect_row_test)
        self.action_online_dis.triggered.connect(self.online_dis_test)
        self.action_resource_tool.triggered.connect(self.resource_test)
        self.action_analysis_record_bag.triggered.connect(self.analysis_record_bag)
        self.action_cut_trajectory_points.triggered.connect(self.cut_trajectory_points)
        self.action_anti_interference_endurance.triggered.connect(self.anti_interference_endurance)

        self.load_data_btn.clicked.connect(self.select_csv_file)
        self.redraw_line_btn.clicked.connect(self.redraw_ab_line)
        self.start_linear_accuracy_test_btn.clicked.connect(self.start_linear_accuracy_test)

        self.point_a_x_text.setText(a_x)
        self.point_a_y_text.setText(a_y)
        self.point_b_x_text.setText(b_x)
        self.point_b_y_text.setText(b_y)

    @QtCore.pyqtSlot()
    def select_csv_file(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        self.csv_file_path, _ = QtWidgets.QFileDialog.getOpenFileName(None, "QFileDialog.getOpenFileName()", "",
                                                                      "CSV Files (*.csv)", options=options)
        self.load_csv_data()

    @QtCore.pyqtSlot()
    def load_csv_data(self):
        if self.csv_file_path:
            _data = np.loadtxt(self.csv_file_path, delimiter=',')
            if _data.shape[-1] > 3:
                self.localization_points_from_csv = np.delete(_data, [0], axis=1).tolist()  # 删除第一列
            else:
                self.localization_points_from_csv = _data[:, [1, 2]].tolist()

            self.matplotlib_view.update_data(self.localization_points_from_csv)
            self.redraw_ab_line()

    @QtCore.pyqtSlot()
    def redraw_ab_line(self):
        _point_a = [float(self.point_a_x_text.text()), float(self.point_a_y_text.text())]
        _point_b = []
        if self.ABLine.isChecked():
            # AB线测试
            _point_b = [float(self.point_b_x_text.text()), float(self.point_b_y_text.text())]
        else:
            _angle = float(self.angle_text.text())
            _offset = float(self.offset_angle_text.text())
            _point_b = get_virtual_point(_point_a, self.localization_points_from_csv[0],
                                         self.localization_points_from_csv[-1], _angle + _offset * math.pi / 180)
        self.matplotlib_view.update_a_b_line([[_point_a[0], _point_b[0]], [_point_a[1], _point_b[1]]])

    @QtCore.pyqtSlot()
    def test_type_changed(self, test_type):
        if test_type == "ab_line":
            self.ABLine.setChecked(True)
            # AB线测试，航向角、偏角、终止线与B点距离不可编辑
            self.angle_text.setEnabled(False)
            self.offset_angle_text.setEnabled(False)
            self.offset_b_to_end_text.setEnabled(False)

            # B点坐标可编辑
            self.point_b_group.setEnabled(True)

            self.point_a_x_text.setText(a_x)
            self.point_a_y_text.setText(a_y)
            self.point_b_x_text.setText(b_x)
            self.point_b_y_text.setText(b_y)

        else:
            self.APlusLine.setChecked(True)
            # A+线测试，航向角、偏角、终止线与B点距离可编辑
            self.angle_text.setEnabled(True)
            self.offset_angle_text.setEnabled(True)
            self.offset_b_to_end_text.setEnabled(True)

            # B点坐标不可编辑
            self.point_b_group.setEnabled(False)

            self.point_a_x_text.setText(a_p_x)
            self.point_a_y_text.setText(a_p_y)
            self.angle_text.setText(theta)
            self.offset_angle_text.setText(theta_offset)

        if self.csv_file_path:
            self.redraw_ab_line()

    @QtCore.pyqtSlot()
    def start_linear_accuracy_test(self):
        _x_points = self.matplotlib_view.point_a_b.get_xdata()
        _y_points = self.matplotlib_view.point_a_b.get_ydata()
        _end_line_dis = float(self.offset_b_to_end_text.text())
        _start_line_dis = float(self.offset_a_to_start_text.text())
        _test_type = "ab_line" if self.ABLine.isChecked() else "a_plus_line"
        _p_obj = GetLocalizationPoints(([_x_points[0], _y_points[0]], [_x_points[1], _y_points[1]]),
                                       _start_line_dis, self.localization_points_from_csv,
                                       self.global_config["aver_count"])
        _res = _p_obj.start_calc(_test_type, _end_line_dis)
        _format_text = format_message_text(_res)
        QMessageBox.information(None, "测试结果", _format_text, QMessageBox.Ok)

    @QtCore.pyqtSlot()
    def set_threshold(self):
        self.dhy_threshold_dialog = DHYThresholdDialog(self.global_config)
        self.dhy_threshold_dialog.threshold_value_changed_signal.connect(self.threshold_value_changed)
        self.dhy_threshold_dialog.exec_()

    @QtCore.pyqtSlot()
    def connect_row_test(self):
        self.dhy_connect_row_view = DHYConnectRowView()
        self.dhy_connect_row_view.show()

    @QtCore.pyqtSlot()
    def online_dis_test(self):
        self.online_dis_test_view = DHYOnlineDisView()
        self.online_dis_test_view.show()

    @QtCore.pyqtSlot()
    def resource_test(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        txt_files_path, _ = QtWidgets.QFileDialog.getOpenFileNames(None, "QFileDialog.getOpenFileName()", "",
                                                                   "CSV Files (*.txt)", options=options)
        if txt_files_path:
            # 将多个文件升序排列，保证多个文件中时间顺序为升序
            txt_files_path.sort()
            show_dhy_resource_collection_view(txt_files_path)

    @QtCore.pyqtSlot()
    def analysis_record_bag(self):
        options = QtWidgets.QFileDialog.Options()
        options |= QtWidgets.QFileDialog.DontUseNativeDialog
        _file_path = QtWidgets.QFileDialog. \
            getExistingDirectory(None, "选择Record文件目录", "",
                                 QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontResolveSymlinks)
        if _file_path:
            record_to_csv(_file_path)
        # _obj = AnalysisRecordBag(".")
        # _obj.get_csv_from_record()

    @QtCore.pyqtSlot()
    def cut_trajectory_points(self):
        self.cut_trajectory_points_view = DHYCutTrajectoryView()
        self.cut_trajectory_points_view.show()

    @QtCore.pyqtSlot()
    def anti_interference_endurance(self):
        self.anti_interference_endurance_view = DHYAntiInterferenceEnduranceView()
        self.anti_interference_endurance_view.show()

    # -------------------------------  修改阈值监听事件  -------------------------------
    def threshold_value_changed(self, threshold_value):
        self.global_config = threshold_value
        self.dhy_threshold_dialog.close()

    def get_clicked_index(self, point_index):
        _point = self.localization_points_from_csv[point_index]
        _x_points = self.matplotlib_view.point_a_b.get_xdata()
        _y_points = self.matplotlib_view.point_a_b.get_ydata()
 
        a, b, c = calc_baseline_equation([_x_points[0], _y_points[0]], [_x_points[1], _y_points[1]])
        _point_to_line = get_distance_of_point_to_line(_point, a, b, c)
        QMessageBox.information(None, "提示", f"此点到参考线距离为: {round(_point_to_line*100, 2)} cm", QMessageBox.Ok)
